package com.conph.rpc.core;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class RpcClient {
	private RpcClientExecutor rpcClientExecutor;
	
	public RpcClient(String rpcServerIp, int rpcServerPort) {
		this.rpcClientExecutor = new RpcClientExecutor(rpcServerIp, rpcServerPort);
	}
	
	@SuppressWarnings("unchecked")
	public <T> T getProxy(Class<?> klass) throws Exception {
		// TODO 判断klass是否是接口；若不是，应该采用cglib代理模式或者抛出异常
		return (T) Proxy.newProxyInstance(
			klass.getClassLoader(), 
			new Class<?>[] { klass },
			new InvocationHandler() {
				@Override
				public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
					String rpcBeanId = String.valueOf(method.toString().hashCode());
					rpcClientExecutor.setReturnType(method.getReturnType());
					Object result = rpcClientExecutor.rpcExecutor(rpcBeanId, args);
					
					return result;
				}
			}
		);
	}
	
}
